<template>
  <div class="register-container">
    <el-card class="register-card">
      <div slot="header" class="card-header">
        <h2>注册</h2>
      </div>
      <el-form
        ref="registerForm"
        :model="registerForm"
        :rules="rules"
        label-width="100px">
        <el-form-item label="用户号" prop="userId">
          <el-input
            v-model="registerForm.userId"
            placeholder="请输入用户号"
            @blur="$refs.registerForm && $refs.registerForm.validateField('userId')">
          </el-input>
          <div class="form-tip">{{ getUserIdTip }}</div>
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="registerForm.name"
            placeholder="请输入姓名">
          </el-input>
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-select
            v-model="registerForm.role"
            placeholder="请选择角色"
            @change="handleRoleChange">
            <el-option label="教师" value="teacher"></el-option>
            <el-option label="学生" value="student"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码">
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码">
          </el-input>
        </el-form-item>

        <el-form-item label="学校" prop="universityName">
          <el-input
            v-model="registerForm.universityName"
            placeholder="请输入学校名称">
          </el-input>
        </el-form-item>

        <el-form-item label="学院" prop="collegeName">
          <el-input
            v-model="registerForm.collegeName"
            placeholder="请输入学院名称">
          </el-input>
        </el-form-item>

        <el-form-item label="专业" prop="majorName">
          <el-input
            v-model="registerForm.majorName"
            placeholder="请输入专业名称">
          </el-input>
        </el-form-item>

        <template v-if="registerForm.role === 'student'">
          <el-form-item label="年级" prop="grade">
            <el-input
              v-model="registerForm.grade"
              placeholder="请输入年级">
            </el-input>
          </el-form-item>

          <el-form-item label="班级" prop="classId">
            <el-input
              v-model="registerForm.classId"
              placeholder="请输入班级">
            </el-input>
          </el-form-item>
        </template>

        <template v-if="registerForm.role === 'teacher'">
          <el-form-item label="年级" prop="teacherGrade" :required="false">
            <el-input
              v-model="registerForm.grade"
              placeholder="请输入带班年级（选填）">
            </el-input>
            <div class="form-tip">如果您负责带班，请填写带班年级，否则可以留空</div>
          </el-form-item>

          <el-form-item label="班级" prop="teacherClassId" :required="false">
            <el-input
              v-model="registerForm.classId"
              placeholder="请输入带班班级（选填）">
            </el-input>
            <div class="form-tip">如果您负责带班，请填写带班班级，否则可以留空</div>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleRegister"
            class="register-button">
            注册
          </el-button>
          <el-button
            type="text"
            @click="$router.push('/admin/login')"
            class="login-link">
            已有账号？立即登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { userApi } from '@/api'

export default {
  name: 'Register',
  data() {
    const validateUserId = (_rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入用户号'))
      }
      const role = this.registerForm.role
      if (role === 'teacher' && !/^\d{6,9}$/.test(value)) {
        callback(new Error('教师用户号必须是6-9位数字'))
      } else if (role === 'student' && !/^\d{10,}$/.test(value)) {
        callback(new Error('学生用户号必须是至少10位数字'))
      } else {
        // 检查用户ID是否已存在
        userApi.getById(value)
          .then(res => {
            if (res.code === 200 && res.data) {
              // 用户ID已存在
              callback(new Error('该用户号已注册，请直接登录'))
            } else {
              // 用户ID不存在，可以注册
              callback()
            }
          })
          .catch(() => {
            // API调用失败，允许继续注册
            callback()
          })
      }
    }

    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      registerForm: {
        userId: '',
        name: '',
        role: '',
        password: '',
        confirmPassword: '',
        universityName: '',
        collegeName: '',
        majorName: '',
        grade: '',
        classId: ''
      },
      rules: {
        userId: [
          { required: true, validator: validateUserId, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { max: 50, message: '姓名长度不能超过50个字符', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        universityName: [
          { required: true, message: '请输入学校名称', trigger: 'blur' }
        ],
        collegeName: [
          { required: true, message: '请输入学院名称', trigger: 'blur' }
        ],
        majorName: [
          { required: true, message: '请输入专业名称', trigger: 'blur' }
        ],
        grade: [
          {
            required: function() {
              return this.registerForm.role === 'student';
            },
            message: '请输入年级',
            trigger: 'blur'
          }
        ],
        classId: [
          {
            required: function() {
              return this.registerForm.role === 'student';
            },
            message: '请输入班级',
            trigger: 'blur'
          }
        ],
        teacherGrade: [],
        teacherClassId: []
      },
      loading: false
    }
  },
  computed: {
    getUserIdTip() {
      const role = this.registerForm.role
      if (role === 'teacher') {
        return '教师用户号必须是6-9位数字'
      } else if (role === 'student') {
        return '学生用户号必须是至少10位数字'
      }
      return ''
    }
  },
  methods: {
    handleRoleChange() {
      this.$refs.registerForm.validateField('userId')
    },
    async handleRegister() {
      try {
        await this.$refs.registerForm.validate()
        this.loading = true

        // 创建用户数据对象
        const userData = {
          userId: this.registerForm.userId,
          name: this.registerForm.name,
          role: this.registerForm.role,
          password: this.registerForm.password,
          universityName: this.registerForm.universityName,
          collegeName: this.registerForm.collegeName,
          majorName: this.registerForm.majorName
        }

        // 如果是学生，必须添加年级和班级
        if (this.registerForm.role === 'student') {
          userData.grade = this.registerForm.grade
          userData.classId = this.registerForm.classId
        }
        // 教师角色，年级和班级是可选的
        else if (this.registerForm.role === 'teacher') {
          // 只有用户输入了值才包含这些字段
          if (this.registerForm.grade) userData.grade = this.registerForm.grade
          if (this.registerForm.classId) userData.classId = this.registerForm.classId
        }

        const res = await userApi.create(userData)

        if (res.code === 200) {
          this.$message.success('注册成功')

          // 保存用户信息到localStorage
          const userInfo = {
            userId: userData.userId,
            name: userData.name,
            role: userData.role,
            universityName: userData.universityName,
            collegeName: userData.collegeName,
            majorName: userData.majorName,
            grade: userData.grade,
            classId: userData.classId
          }
          localStorage.setItem('user', JSON.stringify(userInfo))

          // 根据角色跳转到不同页面
          if (userData.role === 'student') {
            // 学生注册成功后直接跳转到首页
            this.$router.push('/')
          } else if (userData.role === 'teacher') {
            // 教师注册成功后跳转到教师个人中心
            this.$router.push('/teacher/profile')
          }
        } else {
          this.$message.error(res.message || '注册失败')
        }
      } catch (error) {
        console.error('注册错误：', error)
        // 特殊处理用户已存在的错误
        if (error.message && error.message.includes('用户号已注册')) {
          this.$message.info(error.message)
          // 可以添加自动跳转到登录页的逻辑
          setTimeout(() => {
            this.$router.push('/admin/login')
          }, 1500)
        } else {
          this.$message.error('注册失败，请检查输入信息')
        }
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.register-card {
  width: 500px;
  border-radius: 8px;
}

.card-header {
  text-align: center;
  margin-bottom: 20px;
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.register-button {
  width: 100%;
  margin-bottom: 10px;
}

.login-link {
  display: block;
  text-align: center;
  margin-top: 10px;
}
</style>